package command

import (
	"encoding/hex"
	"encoding/json"
	"gdfs-center/db"
	"gdfs-center/engine"
	"gdfs-center/err"
	"gdfs-center/socket/cmdGenerate"
	"gdfs-center/socket/codec"
	"log"
)

//解析心跳
func Analysisheartbeat(data *codec.DataDockPackage) *codec.Response {
	var hearbeatinfo codec.HeartBeatInfo
	var heartBeat db.HeartBeat
	hexbyte, _ := hex.DecodeString(data.Data)
	log.Println("####Cmd:", data.Cmd, "hexdata =", string(hexbyte))
	jsonerr := json.Unmarshal(hexbyte, &hearbeatinfo)
	if jsonerr != nil {
		log.Println("###json err:", jsonerr)
		return codec.GetResponse(2, data.SerialNum, err.JSONERR, err.Errortype[err.JSONERR])
	}
	db.GetDB().Where("store_id = ?", hearbeatinfo.ID).First(&heartBeat)
	if heartBeat != (db.HeartBeat{}) {
		//更新
		er := db.GetDB().Save(&heartBeat).Error
		if er != nil {
			log.Println("###更新失败")
			return codec.GetResponse(2, data.SerialNum, err.SAVEERR, err.Errortype[err.SAVEERR])
		}
	} else {
		heartBeat.StoreId = hearbeatinfo.ID
		er := db.GetDB().Create(&heartBeat).Error
		if er != nil {
			log.Println("###存储失败")
			return codec.GetResponse(2, data.SerialNum, err.SAVEERR, err.Errortype[err.SAVEERR])
		}
	}
	if _, ok := engine.GetEngine().StoreMap[hearbeatinfo.ID]; ok {
		s := engine.GetEngine().StoreMap[hearbeatinfo.ID]
		s.SetAlive(true)
		var store db.Store
		db.GetDB().Where("store_id = ?", hearbeatinfo.ID).First(&store)
		if store != (db.Store{}) {
			var stores []db.Store
			db.GetDB().Where("node_id = ?", store.NodeId).Find(&stores)
			var nstores codec.NoticeNodeCmd
			nstores.NodeID = store.NodeId
			if len(stores) > 0 {
				for _, st := range stores {
					var nst codec.NoticeStore
					nst.StoreId = st.StoreId
					nst.StoreIp = st.StoreIp
					nst.HttpPort = st.HttpPort
					nstores.NoticeStores = append(nstores.NoticeStores, nst)
				}
			} else {
				nstores.NoticeStores = nil
			}
			//发送
			s.Conn.Write(cmdGenerate.GenerateNotisNode(nstores))
		}

	}
	return codec.GetResponse(2, data.SerialNum, err.SUCESS, err.Errortype[err.SUCESS])
}
